'use strict';
const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  console.log('getCustomerServiceChat 接收到的参数:', event);
  
  if (!event.uniIdToken) {
    return {
      code: 401,
      msg: '用户未登录'
    };
  }

  const uniIDIns = uniID.createInstance({ context });

  try {
    const { uid: userId } = await uniIDIns.checkToken(event.uniIdToken);
    if (!userId) {
      return { code: 401, msg: '用户未登录' };
    }

    const { limit = 50, sessionId } = event;

    console.log('查询用户聊天记录，用户ID:', userId);

    // 查询用户与客服的聊天记录
    const result = await db.collection('chatMessages')
      .where(db.command.or([
        {
          senderId: userId,
          receiverId: 'admin'
        },
        {
          senderId: 'admin',
          receiverId: userId
        }
      ]))
      .orderBy('createTime', 'desc')
      .limit(limit)
      .get();

    console.log('查询到的聊天记录数量:', result.data.length);

    // 转换数据格式以适配前端
    const messages = result.data.reverse().map(item => ({
      _id: item._id,
      senderId: item.senderId,
      senderNickname: item.senderNickname,
      senderAvatar: item.senderAvatar,
      content: item.content,
      messageType: item.type,
      createTime: item.createTime,
      status: item.status,
      imageUrl: item.imageUrl,
      card: item.card
    }));

    return {
      code: 200,
      msg: '获取成功',
      data: messages,
      session: {
        _id: sessionId || 'default_session'
      }
    };

  } catch (error) {
    console.error('获取客服聊天记录失败:', error);
    return {
      code: 500,
      msg: '获取聊天记录失败: ' + error.message,
      data: []
    };
  }
};
